package org.zjut.db;


import com.alibaba.fastjson.JSON;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.transaction.annotation.Transactional;
import org.zjut.util.CommonUtil;

import java.util.*;

/**
 * @date 2017/08/14
 * @author  rising
 * @des 学习资源相关操作
 */
public class ResourceDataBase extends JdbcDaoSupport {
    String dataBase = "pso_recommond";
    String tb_resource = ".resource";
    String tb_resourceAttr = ".resource_attr";
    String v_course_knowledge_resource = ".view_course_knowledge_resource";
    /*===================学习资源相关操作=============*/


    /**
     * 获取学习资源和相关属性
     * 某个知识点下面
     * @param params
     * @return
     */
   public Map<String,Object> getResource(Map<String,Object> params){
       String resourceCode = null , conceptCode = null,userCode = null,courseCode = null;
       List<Map<String,Object>> resource;
       Map<String,Object> result = new HashMap<>();
       if(params!=null){
           try{
               if(params.containsKey("conceptCode")){
                   conceptCode = params.get("conceptCode").toString();
               }
               if(params.containsKey("resourceCode")){
                   resourceCode = params.get("resourceCode").toString();
               }
               if(params.containsKey("userCode")){
                   userCode = params.get("userCode").toString();
               }
               if(params.containsKey("courseCode")){
                   courseCode = params.get("courseCode").toString();
               }
           }catch (Exception e){
               return CommonUtil.setErrorInfo("请检查参数");
           }
       }

       String sql = " SELECT a.resourceCode , a.resourceName ,a.describes,a.knowledgeCode as conceptCode ,a.courseCode ," +
               " a.fileUrl as fileUrl FROM "+dataBase+v_course_knowledge_resource+" as a  WHERE 1=1 ";
       if(conceptCode!=null){
           sql = sql + " AND a.konwledgeCode = '"+ conceptCode +"'";
       }
       if(resourceCode!=null){
           //如果带了code 参数，查询条件进行过滤
           sql = sql + " AND a.resourceCode = '"+resourceCode+"'";
       }

       if(userCode!=null){
           sql = sql + " AND a.userCode = '"+userCode+"'";
       }

       if(courseCode!=null){
           sql = sql + " AND a.courseCode = '"+courseCode+"'";
       }



       System.out.println(sql);
       try{
           resource = getJdbcTemplate().queryForList(sql);
           String sql2 = " SELECT * FROM "+dataBase+".view_resource_attr as a where a.resourceCode = ? ";
           List<Map<String,Object>> resourceInfos = new ArrayList<>();
           for(Map<String,Object> item : resource){
               List<Map<String,Object>> attrInfos = getJdbcTemplate().queryForList(sql2,new Object[]{item.get("resourceCode").toString()});
               item.put("attrInfos",attrInfos);
               resourceInfos.add(item);
           }
           Map<String,Object> message = new HashMap<>();
           message.put("resourceInfos",resourceInfos);
           result.put("success",true);
           result.put("message",message);
       }catch (Exception e){
           System.out.println(e.getMessage()+"");
           return CommonUtil.setErrorInfo("查询失败");
       }
       return result;
   }

    /**
     * 添加学习资源
     * 添加资源的基本信息，同时添加的属性值
     * @param params
     * @return
     */
    @Transactional(rollbackFor = java.lang.Exception.class)
    public Map<String,Object> addResource(Map<String,Object> params){
        String resourceName = null ,describe = null , knowledgeCode = null , userCode = null, fileUrl = null;
        List<Map> valueInfo = null ;
        Map<String,Object> result = new HashMap<>();
        try{
            resourceName = params.get("resourceName").toString();
            describe = params.get("describes").toString();
            knowledgeCode = params.get("conceptCode").toString();
            userCode = params.get("userCode").toString();
            fileUrl = params.get("fileUrl").toString();
            fileUrl = fileUrl.replace("\\","/");
            fileUrl = fileUrl.replace("public","");

            valueInfo = JSON.parseArray(params.get("valueInfo").toString(),Map.class) ;
            if(valueInfo == null || valueInfo.size()==0){
                return CommonUtil.setErrorInfo("请求参数有问题");
            }
        }catch (Exception e){
            System.out.println(e.getMessage()+"");
            return CommonUtil.setErrorInfo("请求参数有问题");
        }

        //先生成资源表记录，在生成资源与属性配置记录
        String resourceCode = UUID.randomUUID().toString();
        //新增资源表记录
        String sql = " INSERT INTO "+dataBase+tb_resource+" (code, name,knowledgeCode,_describe,userCode,fileUrl) VALUE (?,?,?,?,?,?) ";
        try{
            Map<String,Object> resourceInfo = new HashMap<>();
            List<Map<String,Object>> resourceAttrInfo = new ArrayList<>();

            int row = getJdbcTemplate().update(sql,new Object[]{resourceCode,resourceName,knowledgeCode,describe,userCode,fileUrl});
            if(row > 0 ){
                for(Map<String,Object> item : valueInfo){
//                    String resourceAttrCode = UUID.randomUUID().toString();
                    String sql2 = " INSERT INTO "+dataBase+tb_resourceAttr+"(resCode,attrCode,attrValue,attrType) VALUES (?,?,?,?)";
                    getJdbcTemplate().update(sql2,new Object[]{resourceCode,item.get("attrCode").toString(),
                            item.get("attrValue").toString(),item.get("attrType").toString()});
                    Map<String,Object> attrValue = new HashMap<>();
                    attrValue.put("attrCode",item.get("attrCode").toString());
                    attrValue.put("attrName",item.get("attrName").toString());
                    attrValue.put("attrValue",item.get("attrValue").toString());
                    attrValue.put("attrType",item.get("attrType").toString());
                    resourceAttrInfo.add(attrValue);
                }
                //组织返回参数
                resourceInfo.put("recourceCode",resourceCode);
                resourceInfo.put("resourceName",resourceName);
                resourceInfo.put("conceptCode",knowledgeCode);
                resourceInfo.put("describes",describe);
                resourceInfo.put("userCode",userCode);

                Map<String,Object> message = new HashMap<>();
                message.put("resourceInfo",resourceInfo);
                result.put("success",true);
                result.put("message",message);
            }else{
                return CommonUtil.setErrorInfo("插入数据失败");
            }
        }catch (Exception e){
            System.out.println(e.getMessage()+"");
            throw e;
        }
        return result;
    }


    /**
     * 编辑资源
     * @param params
     * @return
     */
    @Transactional(rollbackFor = java.lang.Exception.class)
    public Map<String,Object> editResource(Map<String,Object> params){
        Map<String,Object> result = new HashMap<>();
        List<Map> valueInfo = null ;
        String resourceCode,resouceName,describe,fileUrl;
        try{
            resourceCode = params.get("resourceCode").toString();
            resouceName = params.get("resourceName").toString();
            describe = params.get("describes").toString();
            fileUrl = params.get("fileUrl").toString();
            fileUrl = fileUrl.replace("\\","/");
            fileUrl = fileUrl.replace("public","");

            valueInfo = JSON.parseArray(params.get("valueInfo").toString(),Map.class);
            if(valueInfo == null || valueInfo.size()==0){
                return CommonUtil.setErrorInfo("请求参数有问题");
            }
        }catch (Exception e){
            System.out.println(e.getMessage()+"");
            return CommonUtil.setErrorInfo("请检查参数");
        }
        String sql = "UPDATE "+dataBase+tb_resource+" SET name = ?,_describe = ? ,fileUrl = ?  WHERE code = ?";
        try{
            //更新资源名称
            int row = getJdbcTemplate().update(sql,new Object[]{resouceName,describe,fileUrl,resourceCode});
            //先删掉原来的配置表记录
            if(row > 0){
                delResourceAttr(resourceCode);
                //重新添加关系
                for(Map<String,Object> item : valueInfo){
//                    String resourceAttrCode = UUID.randomUUID().toString();
                    String sql2 = " INSERT INTO "+dataBase+tb_resourceAttr+"(resCode,attrCode,attrValue,attrType) VALUES (?,?,?,?)";
                    getJdbcTemplate().update(sql2,new Object[]{resourceCode,item.get("attrCode").toString(),item.get("attrValue").toString(),item.get("attrType").toString()});
                }

                result.put("success",true);
                result.put("message","修改成功");
            }else{
                return CommonUtil.setErrorInfo("修改失败");
            }
        }catch (Exception e){
            System.out.println(e.getMessage()+"");
            throw e;
        }

        return result;
    }

    /**
     * 清空资源属性
     * @param resourceCode
     * @return
     */
    public boolean delResourceAttr(String resourceCode){
        String sql = "DELETE FROM "+dataBase+tb_resourceAttr+" WHERE resCode = ? ";

        try{
            getJdbcTemplate().update(sql,new Object[]{resourceCode});
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage()+"");
            return false;
        }
    }

    /**
     * 删除资源
     * 假删除
     * @param resourceCode
     * @return
     */
    public Map<String,Object> delResource(String resourceCode){
        Map<String,Object> result = new HashMap<>();
        String sql = "UPDATE  "+dataBase+tb_resource+" SET isDelete = 1 WHERE code = ? ";
        try {
            getJdbcTemplate().update(sql,new Object[]{resourceCode});
            //清空资源属性记录-假删除，不需要删除属性
//            delResourceAttr(resourceCode);
            result.put("success",true);
            result.put("message","删除成功");
        }catch (Exception e){
            System.out.println(e.getMessage()+"");
            return CommonUtil.setErrorInfo("删除失败");
        }
        return result;
    }

}
